import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent, AlertOptions, BadgePipe, getProperty, MessageService, ModalComponent, Page, paginationFactory, PaginationService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {ChargeRecordFormatterService} from '../../../../services/formatter/charge-record-formatter.service';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Router} from '@angular/router';

const paginationProvider = {
    provide: PaginationService,
    useFactory: paginationFactory,
    deps: [HttpClient, TicketService]
};

@Component({
    selector: 'charge-manager',
    templateUrl: './charge-manager.component.html',
    styleUrls: ['./charge-manager.component.scss'],
    providers: [paginationProvider, ChargeRecordFormatterService, BadgePipe]
})
export class ChargeManagerComponent implements OnInit, AfterViewInit {
    @ViewChild('modal') modal: ModalComponent;
    breadcrumb = [
        {name: '充值管理', cssIcon: 'fa fa-fw fa-jpy'}
    ];
    currentRowIndex;
    @ViewChild('alert') alert: AlertComponent;
    alertOptions: AlertOptions = {
        theme: 'danger',
        data: null,
        position: 'center'
    };
    page = 1;
    confirmData;
    cancelData;
    removeData;
    chargeTable = new Table({
        headers: this.chargeFormatter.formatter,
    });
    buttons = [];

    constructor(private message: MessageService,
                public pagination: PaginationService,
                private chargeFormatter: ChargeRecordFormatterService,
                private ticketService: TicketService,
                private router: Router,
    ) {
    }

    ngOnInit() {
        this.getInfo(1);

    }

    getInfo(page) {
        this.pagination.simpleFormatter = this.chargeTable.options.headers;
        this.ticketService.get(this.ticketService.urls.getOrderList, {
            observe: 'response',
            params: new HttpParams()
                .append('web_token', localStorage.getItem('token'))
                .append('orderType', '1')
                .append('pageNum', page + '')
                .append('pageSize', '10')
                .append('status', '0')
                .append('needFilter', '0')
        }).subscribe((resp) => {
            if (resp.body.success) {
                const result = resp.body.returnValue.page;
                this.pagination.page.results = result.list;
                this.pagination.page.totalPage = result.pages;
                this.pagination.page.pageNumber = result.pageNum;
                this.pagination.page.pageSize = result.pageSize;
                this.pagination.formatData();
                this.pagination.dataLoadSubscriber$.subscribe(() => {
                    this.message.sendMessage('page load progress', this);
                    for (const item of this.pagination.page.results) {
                        let buttonItem = [];
                        if (item.status === 0) {
                            buttonItem = [{
                                btnClass: 'btn-success p-1',
                                text: '确认',
                                isShow: true,
                                click: (e) => {
                                    this.showConfirmModal(e);
                                }
                            },
                                {
                                    btnClass: 'btn-secondary p-1',
                                    text: '取消',
                                    isShow: true,
                                    click: (e) => {
                                        this.showCancelModal(e);
                                    }
                                },
                                {
                                    btnClass: 'btn-danger p-1',
                                    text: '撤销',
                                    isShow: false,
                                    click: (e) => {
                                        this.showRemoveModal(e);
                                    }
                                },
                            ];
                        }
                        if (item.status === 2) {
                            buttonItem = [{
                                btnClass: 'btn-success p-1',
                                text: '确认',
                                isShow: false,
                                click: (e) => {
                                    this.showConfirmModal(e);
                                }
                            },
                                {
                                    btnClass: 'btn-secondary p-1',
                                    text: '取消',
                                    isShow: false,
                                    click: (e) => {
                                        this.showCancelModal(e);
                                    }
                                },
                                {
                                    btnClass: 'btn-danger p-1',
                                    text: '撤销',
                                    isShow: true,
                                    click: (e) => {
                                        this.showRemoveModal(e);
                                    }
                                },
                            ];
                        }
                        if (item.status === 1) {
                            buttonItem = [{
                                btnClass: 'btn-success p-1',
                                text: '确认',
                                isShow: false,
                                click: (e) => {
                                    this.showConfirmModal(e);
                                }
                            },
                                {
                                    btnClass: 'btn-secondary p-1',
                                    text: '取消',
                                    isShow: false,
                                    click: (e) => {
                                        this.showCancelModal(e);
                                    }
                                },
                                {
                                    btnClass: 'btn-danger p-1',
                                    text: '撤销',
                                    isShow: false,
                                    click: (e) => {
                                        this.showRemoveModal(e);
                                    }
                                },
                            ];
                        }
                        this.buttons.push(buttonItem);
                    }
                });
            } else {
                this.router.navigateByUrl('/login').catch();
            }
            /** 绑定事件 */
        });
    }

    btnClicked(e, btnIndex, rowIndex) {
        this.currentRowIndex = rowIndex;
        const data = this.pagination.page.results[rowIndex];
        const func = this.buttons[rowIndex][btnIndex].click;
        e.stopPropagation();
        if (typeof func === 'function') {
            this.buttons[rowIndex][btnIndex].click(data, rowIndex);
        }
    }

    firstPage() {
        this.page = 1;
        this.buttons = [];
        this.getInfo(1);
    }

    previousPage() {
        this.buttons = [];
        if (this.page > 1) {
            this.page = this.page - 1;
        } else {
            this.page = 1;
        }
        this.getInfo(this.page);
    }

    nextPage() {
        this.buttons = [];
        if (this.page < this.pagination.page.totalPage) {
            this.page = this.page + 1;
        } else {
            this.page = this.pagination.page.totalPage;
        }
        this.getInfo(this.page);
    }

    lastPage() {
        this.buttons = [];
        this.page = this.pagination.page.totalPage;
        this.getInfo(this.pagination.page.totalPage);
    }

    get getProperty() {
        return getProperty;
    }

    showConfirmModal(item: any) {
        const options = {
            id: 'confirmItem',
            title: '处理订单',
            cssIcon: 'fa fa-fw fa-warning',
            size: 'sm',
            theme: 'danger',
            backdrop: 'static',
            data: '是否审核通过该订单？',
            closeBtn: true,
            confirmBtn: true
        };
        this.modal.show(options);
        this.confirmData = item;
    }

    confirmItem() {
        this.ticketService.post(this.ticketService.urls.dealOrder, {'id': this.confirmData.id, 'status': 1}, {
            observe: 'response',
            params: new HttpParams().append('web_token', localStorage.getItem('token'))
        }).subscribe((resp) => {
            if (resp.body.success) {
                this.buttons = [];
                this.getInfo(this.page);
            } else {
                this.alertOptions.data = resp.body.msg;
                this.alert.show(this.alertOptions, 2000);
            }
        });
    }

    showCancelModal(item: any) {
        const options = {
            id: 'cancelItem',
            title: '处理订单',
            cssIcon: 'fa fa-fw fa-warning',
            size: 'sm',
            theme: 'danger',
            backdrop: 'static',
            data: '是否取消该订单？',
            closeBtn: true,
            confirmBtn: true
        };
        this.modal.show(options);
        this.cancelData = item;
    }

    cancelItem() {
        this.ticketService.post(this.ticketService.urls.dealOrder, {'id': this.cancelData.id, 'status': 2}, {
            observe: 'response',
            params: new HttpParams().append('web_token', localStorage.getItem('token'))
        }).subscribe((resp) => {
            if (resp.body.success) {
                this.buttons = [];
                this.getInfo(this.page);
            } else {
                this.alertOptions.data = resp.body.msg;
                this.alert.show(this.alertOptions, 2000);
            }
        });
    }

    showRemoveModal(item: any) {
        const options = {
            id: 'removeItem',
            title: '处理订单',
            cssIcon: 'fa fa-fw fa-warning',
            size: 'sm',
            theme: 'danger',
            backdrop: 'static',
            data: '是否撤销该订单？',
            closeBtn: true,
            confirmBtn: true
        };
        this.modal.show(options);
        this.removeData = item;
    }

    removeItem() {
        this.ticketService.post(this.ticketService.urls.dealOrder, {'id': this.removeData.id, 'status': 0}, {
            observe: 'response',
            params: new HttpParams().append('web_token', localStorage.getItem('token'))
        }).subscribe((resp) => {
            if (resp.body.success) {
                this.buttons = [];
                this.getInfo(this.page);
            } else {
                this.alertOptions.data = resp.body.msg;
                this.alert.show(this.alertOptions, 2000);
            }
        });
    }

    eventHandler() {
        this.modal.event.subscribe({
            next: (event) => {
                if (event.name === 'confirm' && event.id === 'confirmItem') {
                    this.modal.hide();
                    this.confirmItem();
                }
                if (event.name === 'confirm' && event.id === 'cancelItem') {
                    this.modal.hide();
                    this.cancelItem();
                }
                if (event.name === 'confirm' && event.id === 'removeItem') {
                    this.modal.hide();
                    this.removeItem();
                }
            }
        });
    }

    ngAfterViewInit(): void {
        this.eventHandler();
        this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
        this.message.sendMessage('page load progress', this, '300ms');
    }

}
